package db

import (
	"errors"
	myorm "filestore-rebuild/db/orm"
	"filestore-rebuild/models"
)

func InsertUserFileORM(userFile *models.UserFile) error {
	var tmpUserfile models.UserFile
	db := myorm.GetDB()
	db.Where(
		"user_name = ? and file_sha1 = ? and file_name = ?",
		userFile.UserName, userFile.FileSha1, userFile.FileName,
	).First(&tmpUserfile)
	if tmpUserfile.UserName == userFile.UserName &&
		tmpUserfile.FileSha1 == userFile.FileSha1 &&
		tmpUserfile.FileName == tmpUserfile.FileName {
		return errors.New("file exists")
	}
	db.Create(&userFile)
	return nil
}

func ListUserFile(username string) []models.UserFile {
	var userFiles []models.UserFile
	db := myorm.GetDB()
	db.Find(&userFiles, map[string]interface{}{"user_name": username})
	return userFiles
}

func DeleteUserFileORM(file models.UserFile) bool {
	var tmpUserFile models.UserFile
	db := myorm.GetDB()
	db.Where(
		"user_name = ? and file_name = ? and file_sha1 = ?",
		file.UserName, file.FileName, file.FileSha1,
	).First(&tmpUserFile)
	if tmpUserFile.FileSha1 != file.FileSha1 {
		return false
	}

	db.Delete(&tmpUserFile)
	return true
}

func UpdateUserFileNameORM(userFile models.UserFile, newName string) bool {
	var tmpUserfile models.UserFile
	db := myorm.GetDB()
	db.Where(
		"user_name = ? and file_sha1 = ? and file_name = ?",
		userFile.UserName, userFile.FileSha1, userFile.FileName,
	).First(&tmpUserfile)
	if tmpUserfile.ID == 0 {
		return false
	}
	db.Model(&userFile).Update("file_name", newName)
	return true
}

func SelectUserFile(userName, fileName, fileSha1 string) (models.UserFile, error) {
	var userFile models.UserFile
	db := myorm.GetDB()
	db.Where(
		"user_name = ? and file_name = ? and file_sha1 = ?",
		userName, fileName, fileSha1,
	).First(&userFile)
	if userFile.ID == 0 {
		return userFile, errors.New("file not exists")
	}
	return userFile, nil
}
